// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
})

// 云函数入口函数
exports.main = async (event, context) => {

  // 获取微信上下文
  const wxContext = cloud.getWXContext();

  /** 检查传入参数是否完整 start */
  if(event.building == undefined || event.room == undefined || event.date == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未传入必要参数";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查传入参数是否完整 end */

  // 获得数据库实例
  const db = cloud.database();

  /** 查询该用户已注册绑定的室友（家庭成员） start */
  var roomate = [];
  await db.collection('userInfo')
  .where({
    building: event.building,
    room: event.room
  })
  .get()
  .then(res => {
    console.log(res.data);
    roomate = res.data;
  })
  /** 查询该用户已注册绑定的室友（家庭成员） end */

  /** 查询每个成员今日的健康打卡完成情况 start */
  var recordState = [];
  var n = roomate.length;
  for (var i = 0; i < n; i++) {
    var state = {};  // 存放每个成员的姓名以及今日打卡完成情况
    var record = [];  // 存放一个成员今日的健康记录
    state.openId = roomate[i].openId;
    state.name = roomate[i].name;
    await db.collection('healthReport')  // 查询每个成员今日的打卡次数
    .where({
      openId: roomate[i].openId,
      date: event.date
    })
    .get()
    .then(res => {
      console.log(res.data);
      record = res.data;
    })
    var cnt = record.length;
    if(cnt == 3) {
      console.log(roomate[i].name + "完成了今日的健康上报");
      state.isComplete = true;
    } else {
      console.log(roomate[i].name + "未完成今日的健康上报");
      state.isComplete = false;
    }
    state.cnt = cnt;
    recordState.push(state);
  }
  /** 查询每个成员今日的健康打卡完成情况 end */

  // 返回数据
  var result = {};
  result.errCode = 0;
  result.errMsg = "查询成功";
  var data = {};
  data.recordState = recordState;
  result.data = data;
  return result;
}